<template>
  <div class="app-container">
    <!-- 设备基本信息 -->
    <el-card class="box-card" style="margin-bottom: 20px">
      <div slot="header" class="clearfix">
        <span><i class="el-icon-monitor"></i> 设备基本信息</span>
      </div>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="设备名称">{{ deviceInfo.deviceName }}</el-descriptions-item>
        <el-descriptions-item label="设备编号">{{ deviceInfo.deviceCode }}</el-descriptions-item>
        <el-descriptions-item label="设备类型">{{ deviceInfo.deviceType }}</el-descriptions-item>
        <el-descriptions-item label="设备状态">
          <el-tag :type="deviceInfo.status === '1' ? 'success' : 'danger'">
            {{ deviceInfo.status === '1' ? '在线' : '离线' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="安装位置">{{ deviceInfo.location }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ parseTime(deviceInfo.createTime) }}</el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 设备参数配置 -->
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span><i class="el-icon-setting"></i> 设备参数配置</span>
        <div style="float: right;">
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-upload2"
            @click="handleImportConfig"
            v-hasPermi="['system:device:import']"
          >导入配置</el-button>
          <el-button
            size="mini"
            type="success"
            icon="el-icon-download"
            @click="handleExportConfig"
            v-hasPermi="['system:device:export']"
          >导出配置</el-button>
        </div>
      </div>

      <!-- 搜索区域 -->
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="参数名称" prop="paramName">
          <el-input
            v-model="queryParams.paramName"
            placeholder="请输入参数名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="参数类型" prop="paramType">
          <el-select v-model="queryParams.paramType" placeholder="请选择参数类型" clearable>
            <el-option label="字符串" value="string" />
            <el-option label="数字" value="number" />
            <el-option label="布尔值" value="boolean" />
            <el-option label="JSON" value="json" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 操作按钮 -->
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['system:device:add']"
          >新增参数</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:device:edit']"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:device:remove']"
          >删除</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getParamList"></right-toolbar>
      </el-row>

      <!-- 参数表格 -->
      <el-table v-loading="loading" :data="paramList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="参数名称" align="center" prop="paramName" :show-overflow-tooltip="true" />
        <el-table-column label="参数键" align="center" prop="paramKey" :show-overflow-tooltip="true" />
        <el-table-column label="参数值" align="center" prop="paramValue" :show-overflow-tooltip="true" />
        <el-table-column label="参数类型" align="center" prop="paramType">
          <template slot-scope="scope">
            <el-tag :type="getParamTypeTag(scope.row.paramType)">{{ scope.row.paramType }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="是否必填" align="center" prop="required">
          <template slot-scope="scope">
            <el-tag :type="scope.row.required === '1' ? 'danger' : 'info'">
              {{ scope.row.required === '1' ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="描述" align="center" prop="description" :show-overflow-tooltip="true" />
        <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.updateTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:device:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:device:remove']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getParamList"
      />
    </el-card>

    <!-- 参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="参数名称" prop="paramName">
          <el-input v-model="form.paramName" placeholder="请输入参数名称" />
        </el-form-item>
        <el-form-item label="参数键" prop="paramKey">
          <el-input v-model="form.paramKey" placeholder="请输入参数键" />
        </el-form-item>
        <el-form-item label="参数值" prop="paramValue">
          <el-input v-model="form.paramValue" type="textarea" :rows="3" placeholder="请输入参数值" />
        </el-form-item>
        <el-form-item label="参数类型" prop="paramType">
          <el-select v-model="form.paramType" placeholder="请选择参数类型">
            <el-option label="字符串" value="string" />
            <el-option label="数字" value="number" />
            <el-option label="布尔值" value="boolean" />
            <el-option label="JSON" value="json" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否必填" prop="required">
          <el-radio-group v-model="form.required">
            <el-radio label="1">是</el-radio>
            <el-radio label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="参数描述" prop="description">
          <el-input v-model="form.description" type="textarea" :rows="2" placeholder="请输入参数描述" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 导入配置对话框 -->
    <el-dialog title="导入设备配置" :visible.sync="importDialog.open" width="500px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".json,.xlsx,.xls"
        :headers="importDialog.headers"
        :action="importDialog.url"
        :disabled="importDialog.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :on-error="handleFileError"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击选择文件</em></div>
        <div class="el-upload__tip" slot="tip">
          <div class="el-upload__tip">
            <el-checkbox v-model="importDialog.updateSupport" />是否更新已经存在的参数配置
          </div>
          <span>支持导入json、xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="downloadTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="importDialog.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getDevice, listDeviceParam, updateDeviceParam, importDeviceConfig } from "@/api/system/device"
import { getToken } from "@/utils/auth"

export default {
  name: "DeviceDetail",
  data() {
    return {
      // 设备ID
      deviceId: null,
      // 设备信息
      deviceInfo: {},
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 参数表格数据
      paramList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        paramName: null,
        paramType: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        paramName: [
          { required: true, message: "参数名称不能为空", trigger: "blur" }
        ],
        paramKey: [
          { required: true, message: "参数键不能为空", trigger: "blur" }
        ],
        paramValue: [
          { required: true, message: "参数值不能为空", trigger: "blur" }
        ],
        paramType: [
          { required: true, message: "参数类型不能为空", trigger: "change" }
        ]
      },
      // 导入配置对话框参数
      importDialog: {
        // 是否显示弹出层
        open: false,
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的参数配置
        updateSupport: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/device/importConfig"
      }
    }
  },
  created() {
    this.deviceId = this.$route.params && this.$route.params.deviceId
    if (this.deviceId) {
      this.getDeviceInfo()
      this.getParamList()
    }
  },
  methods: {
    /** 获取设备信息 */
    getDeviceInfo() {
      getDevice(this.deviceId).then(response => {
        this.deviceInfo = response.data
      })
    },
    /** 查询参数列表 */
    getParamList() {
      this.loading = true
      const params = {
        ...this.queryParams,
        deviceId: this.deviceId
      }
      listDeviceParam(this.deviceId).then(response => {
        this.paramList = response.rows || []
        this.total = response.total || 0
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        paramId: null,
        deviceId: this.deviceId,
        paramName: null,
        paramKey: null,
        paramValue: null,
        paramType: "string",
        required: "0",
        description: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getParamList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加设备参数"
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.paramId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const paramId = row.paramId || this.ids
      // 这里应该调用获取参数详情的API，暂时用row数据
      this.form = { ...row }
      this.open = true
      this.title = "修改设备参数"
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.paramId != null) {
            updateDeviceParam(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getParamList()
            })
          } else {
            updateDeviceParam(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getParamList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const paramIds = row.paramId || this.ids
      this.$modal.confirm('是否确认删除参数编号为"' + paramIds + '"的数据项？').then(function() {
        // 这里应该调用删除参数的API
        return Promise.resolve()
      }).then(() => {
        this.getParamList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导入配置按钮操作 */
    handleImportConfig() {
      this.importDialog.open = true
      this.importDialog.url = process.env.VUE_APP_BASE_API + "/system/device/" + this.deviceId + "/importConfig"
    },
    /** 导出配置按钮操作 */
    handleExportConfig() {
      this.download('system/device/' + this.deviceId + '/exportConfig', {
        ...this.queryParams
      }, `device_config_${this.deviceId}_${new Date().getTime()}.xlsx`)
    },
    /** 下载模板 */
    downloadTemplate() {
      this.download('system/device/configTemplate', {}, `device_config_template.xlsx`)
    },
    /** 文件上传中处理 */
    handleFileUploadProgress(event, file, fileList) {
      this.importDialog.isUploading = true
    },
    /** 文件上传成功处理 */
    handleFileSuccess(response, file, fileList) {
      this.importDialog.open = false
      this.importDialog.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true })
      this.getParamList()
    },
    /** 文件上传失败处理 */
    handleFileError(err, file, fileList) {
      this.importDialog.isUploading = false
      this.$modal.msgError("上传失败，请重试")
    },
    /** 提交上传文件 */
    submitFileForm() {
      this.$refs.upload.submit()
    },
    /** 获取参数类型标签样式 */
    getParamTypeTag(type) {
      const typeMap = {
        'string': '',
        'number': 'success',
        'boolean': 'warning',
        'json': 'info'
      }
      return typeMap[type] || ''
    }
  }
}
</script>

<style scoped>
.box-card {
  margin-bottom: 20px;
}
.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}
</style> 